﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Evaluant.Uss;
using Evaluant.Uss.Common;
using System.Security;

namespace EussSimpleDBProvider
{
    public class SimpleDBFactory : PersistenceEngineFactoryImplementation
    {
        string awsId;
        string awsSecretKey;
        string domain;

        public override void InitializeConfiguration()
        {
         
        }

        public SimpleDBFactory() { }

        public string AwsKey
        {
            get { return awsId; }
            set { awsId = value; }
        }

        public string AwsSecret
        {
            get { return awsSecretKey; }
            set { awsSecretKey = value; }
        }

        public string SimpleDBDomain
        {
            get { return domain; }
            set { domain = value; }
        }

        public override IPersistenceEngine CreatePersistenceEngine()
        {
            Amazon.SimpleDB.AmazonSimpleDBClient client = new Amazon.SimpleDB.AmazonSimpleDBClient(awsId, awsSecretKey);

            Amazon.SimpleDB.Model.ListDomainsRequest ld = new Amazon.SimpleDB.Model.ListDomainsRequest();
            ld.MaxNumberOfDomains = 100;
            Amazon.SimpleDB.Model.ListDomainsResponse response = client.ListDomains(ld);

            bool domainexists = false;
            foreach (string name in response.ListDomainsResult.DomainName)
            {
                if (name == domain)
                {
                    //Amazon.SimpleDB.Model.DeleteDomainResponse dr = client.DeleteDomain(new Amazon.SimpleDB.Model.DeleteDomainRequest().WithDomainName("Test"));
                    domainexists = true;
                    break;
                }
            }

            if (!domainexists)
            {
                Amazon.SimpleDB.Model.CreateDomainRequest cd = new Amazon.SimpleDB.Model.CreateDomainRequest();
                cd.DomainName = domain;
                client.CreateDomain(cd);
            }

            return new SimpleDBEngine(client, domain, _Model);
        }
    }
}
